import {Util} from "@lowcode/jpaas-base-lib"
import {defineAsyncComponent} from "vue";
export default {
	provide() {
		return {
			screenVm: this
		}
	},
	data() {
		return {
			customComponents:{},//注册的自定义组件
			componentNum:0,//已注册的自定义组件数量
		}
	},
	methods:{
		//初始化js
		initJsScript(jsScript){
			if (!jsScript) {
				return;
			}
			jsScript=eval('('+Util.replaceDefault(jsScript)+')')
			// //定义数据
			// if(jsScript.data){
			// 	for(let key in jsScript.data()){
			// 		let value=jsScript.data()[key];
			// 		//设置双向绑定值
			// 		Vue.util.defineReactive(this,key,value);
			// 	}
			// }
			//定义方法
			if(jsScript.methods){
				for(let method in jsScript.methods){
					this[method]=jsScript.methods[method];
				}
			}
			//定义监听
			if(jsScript.watch){
				for(let watch in jsScript.watch){
					let json=jsScript.watch[watch];
					if(typeof json == "function"){
						this.$watch(watch, json);
					}else{
						let handler=json.handler;
						delete json.handler;
						this.$watch(watch, handler,json);
					}
				}
			}
			//加载方法
			if(jsScript.created){
				jsScript.created.apply(this);
			}
			if(jsScript.mounted){
				jsScript.mounted.apply(this);
			}
		},
		//获取自定义组件实例
		getCustomComponent(key){
			if(!this.customComponents[key]){
				return {};
			}
			return this.customComponents[key].$refs.customComponent.$refs.controllerView;
		},
        loadView(view) { // 路由懒加载
            let modules = import.meta.glob('@/views/**/*.vue');
            let url = view.includes(".vue") ? view : view + ".vue";
            let component = defineAsyncComponent(modules[`/src/views/${url}`])
            return component;
        }
	},
	watch:{
		componentNum:{
			handler: function (val, oldVal) {
				if(!this.screenConfig || !this.screenConfig.components){
					if(this.onload_){
						this.onload_();
					}
					return;
				}
				let allComponentNum=0;
				for (let i = 0; i < this.screenConfig.components.length; i++) {
					if(this.screenConfig.components[i].type=="custom"){
						allComponentNum++;
					}
				}
				if(allComponentNum===val && this.onload_){
					this.onload_();
				}
			},
			deep: true
		},
	}

}
